﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ERPStudio;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


namespace ESRP
{
    public partial class ConturiSpecialeFrm : FrmRezumat
    {
        private String Cont = String.Empty;
        private String InitValue = String.Empty;
        private String ContParinte = String.Empty;
        private Byte Categorie = 0;
        private Boolean Terminal = true;
        public Boolean MustRefresh = false;
        private Boolean EsteAnalitic = false;
        public ConturiSpecialeFrm(String _cont, String _contParinte, Byte _categorie, Boolean _terminal,Boolean _esteanalitic, ModuleClass mInfo)
            : base(mInfo)
        {
            EsteAnalitic = _esteanalitic;
            Cont = _cont;
            ContParinte = _contParinte;
            Categorie = _categorie;
            Terminal = _terminal;
            InitializeComponent();
            
            if (ModuleInfo.AnArhiva != String.Empty)
                this.ReadOnly = true;
            categorieSursaBindingSource.List.Add(new CategorieSursa("Conturi in bilant", 0));
            //categorieSursaBindingSource.List.Add(new CategorieSursa("Conturi de gestiune", 1));
            categorieSursaBindingSource.List.Add(new CategorieSursa("Conturi in afara bilantului", 2));
            categorieSursaBindingSource.List.Add(new CategorieSursa("Clasa sau Grupa", 3));
            ActiveControl = PropCLB;
        }

        private void ConturiSpecialeFrm_Load(object sender, EventArgs e)
        {
            SetCurentUnit(ModuleInfo.CodUnitate);
            if (ModuleInfo.AnArhiva == String.Empty)
            {
                AddButton("Analitice >>>", global::ERPStudio.Properties.Resources.prezinta, GenerareAnalitice, ToolStripItemAlignment.Right, true);
                ///nu sterge niciodata linia urmatoare
                AddButton("Salvare", global::ERPStudio.Properties.Resources.salvare1, UpdateProp, ToolStripItemAlignment.Right, true);
                HandleSalvare += new EventHandler(UpdateProp);
            }
            //ContParinteCB.Enabled = Terminal;

        }

        private void GenerareAnalitice(object sender, EventArgs e)
        { 
        
        }

        private void UpdateProp(object sender, EventArgs e)
        {
            String rez = String.Empty;
            if (PropCLB.GetItemCheckState(0) == CheckState.Checked)
                rez += "{AA}";
            if (PropCLB.GetItemCheckState(1) == CheckState.Checked)
                rez += "{REX}";
            if (PropCLB.GetItemCheckState(2) == CheckState.Checked)
                rez += "{CCS}";
            if (PropCLB.GetItemCheckState(3) == CheckState.Checked)
                rez += "{CA}";
            if (PropCLB.GetItemCheckState(4) == CheckState.Checked)
                rez += "{CD}";
            if (PropCLB.GetItemCheckState(5) == CheckState.Checked)
                rez += "{AB}";
            if (PropCLB.GetItemCheckState(6) == CheckState.Checked)
                rez += "{AL}";
            if (PropCLB.GetItemCheckState(7) == CheckState.Checked)
                rez += "{EAL}";
            if (PropCLB.GetItemCheckState(8) == CheckState.Checked)
                rez += "{FRZ}";
            if (PropCLB.GetItemCheckState(9) == CheckState.Checked)
                rez += "{TGC}";
            if (PropCLB.GetItemCheckState(10) == CheckState.Checked)
                rez += "{CSS}";
            if (PropCLB.GetItemCheckState(11) == CheckState.Checked)
                rez += "{TVA.DED}";
            if (PropCLB.GetItemCheckState(12) == CheckState.Checked)
                rez += "{TVA.COL}";
            if (PropCLB.GetItemCheckState(13) == CheckState.Checked)
                rez += "{TVA.NED}";
            if (PropCLB.GetItemCheckState(14) == CheckState.Checked)
                rez += "{ADA}";
            if (PropCLB.GetItemCheckState(15) == CheckState.Checked)
                rez += "{CLT}";
            if (PropCLB.GetItemCheckState(16) == CheckState.Checked)
                rez += "{BUG}";
            int cate = 0;
            SqlConnection con = DeschideConexiune(workConnString);
            #region Verifica unicitatea conturilor de TVA
            if (rez.Contains("{TVA.DED}") )
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.DED}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA deductibil!","Eroare",MessageBoxButtons.OK,MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            }

            if (rez.Contains("{TVA.COL}"))
            {
                SqlCommand cmd2 = new SqlCommand("SELECT COUNT(*)  FROM[ConturiSpeciale] WHERE [Tipuri]='{TVA.COL}' AND [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]<>'" +
                Cont + "'", con);
                cate = Convert.ToInt32(cmd2.ExecuteScalar());
                if (cate != 0)
                {
                    MessageBox.Show("Exista definit un cont pentru TVA colectat!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    InchideConexiune(con);
                    return;
                }
            } 

            #endregion


            SqlCommand cmd = new SqlCommand("UPDATE [ConturiSpeciale] SET [Tipuri]='" + rez + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                Cont + "'", con);
            if (InitValue != rez)
            {
                if (InitValue == String.Empty)
                {
                    cmd.CommandText = "INSERT INTO [ConturiSpeciale]([Cont],[CodUnitate],[Tipuri],[Descriere]) VALUES ('" + Cont + "'," + ModuleInfo.CodUnitate.ToString() +
                        ",'" + rez + "','')";
                }
                if (rez == String.Empty)
                {
                    cmd.CommandText = "DELETE FROM [ConturiSpeciale] WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                        Cont + "'";
                }
                try
                {
                    cate += cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    TrateazaExceptie(ex);
                }
            }
            if (ContParinteCB.SelectedValue!=null && ContParinteCB.SelectedValue.ToString() != ContParinte)
            {
                cmd.CommandText = "UPDATE [Conturi] SET [ContParinte] ='" + ContParinteCB.SelectedValue + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                    Cont + "'";
                MustRefresh = true;
                cate += cmd.ExecuteNonQuery();
            }

            if (CategorieCB.SelectedValue!=null && Convert.ToByte(CategorieCB.SelectedValue) != Categorie)
            {
                cmd.CommandText = "UPDATE [Conturi] SET [Categorie] ='" + CategorieCB.SelectedValue.ToString() + "' WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                    Cont + "'";
                MustRefresh = true;
                cate += cmd.ExecuteNonQuery();
            }
            if (AnaliticCB.Checked != EsteAnalitic)
            {
                cmd.CommandText = "UPDATE [Conturi] SET [EsteAnalitic] =" + (AnaliticCB.Checked?"1":"0") + " WHERE [CodUnitate]=" + ModuleInfo.CodUnitate + " AND [Cont]='" +
                    Cont + "'";
                MustRefresh = true;
                cate += cmd.ExecuteNonQuery();    
            }
            
            SetStatus("S-au salvat " + cate.ToString() + " inregistrari la: " + DateTime.Now.ToString());

            InchideConexiune(cmd.Connection);

        }

        override public void SetCurentUnit(short vCodUnitate)
        {
            SqlCommand cmd = new SqlCommand("SELECT [Tipuri] FROM [ConturiSpeciale] WHERE [CodUnitate]=" + vCodUnitate.ToString() + " AND [Cont]='" +
            Cont + "'", DeschideConexiune(workConnString));
            Object rez = cmd.ExecuteScalar();
            if (rez != null && rez != DBNull.Value)
            {
                InitValue = rez.ToString().ToUpper();
                MatchCollection m = Regex.Matches(InitValue,
                @"(\s*{(?<valoare>AA|REX|CA|CD|AB|AL|EAL|CCS|FRZ|TGC|CSS|TVA.DED|TVA.COL|TVA.NED|ADA|CLT|BUG)}\s*)");

                foreach (Match mp in m)
                {
                    if (mp.Success == true)
                    {
                        if (mp.Value == "{AA}")
                            PropCLB.SetItemChecked(0, true);
                        if (mp.Value == "{REX}")
                            PropCLB.SetItemChecked(1, true);
                        if (mp.Value == "{CCS}")
                            PropCLB.SetItemChecked(2, true);
                        if (mp.Value == "{CA}")
                            PropCLB.SetItemChecked(3, true);
                        if (mp.Value == "{CD}")
                            PropCLB.SetItemChecked(4, true);
                        if (mp.Value == "{AB}")
                            PropCLB.SetItemChecked(5, true);
                        if (mp.Value == "{AL}")
                            PropCLB.SetItemChecked(6, true);
                        if (mp.Value == "{EAL}")
                            PropCLB.SetItemChecked(7, true);
                        if (mp.Value == "{FRZ}")
                            PropCLB.SetItemChecked(8, true);
                        if (mp.Value == "{TGC}")
                            PropCLB.SetItemChecked(9, true);
                        if (mp.Value == "{CSS}")
                            PropCLB.SetItemChecked(10, true);
                        if (mp.Value == "{TVA.DED}")
                            PropCLB.SetItemChecked(11, true);
                        if (mp.Value == "{TVA.COL}")
                            PropCLB.SetItemChecked(12, true);
                        if (mp.Value == "{TVA.NED}")
                            PropCLB.SetItemChecked(13, true);
                        if (mp.Value == "{ADA}")
                            PropCLB.SetItemChecked(14, true);
                        if (mp.Value == "{CLT}")
                            PropCLB.SetItemChecked(15, true);
                        if (mp.Value == "{BUG}")
                            PropCLB.SetItemChecked(16, true);

                    }
                }
            }
            conturiTableAdapter.Connection = cmd.Connection;
            conturiTableAdapter.FillByCategorieAll(eSRPDataSet.Conturi, Categorie, ModuleInfo.CodUnitate);
            ContParinteCB.SelectedValue = ContParinte;
            CategorieCB.SelectedValue = (Int16)Categorie;
            AnaliticCB.Checked = EsteAnalitic;
            InchideConexiune(cmd.Connection);
        }

        override public void SetCurentMonth(short vCodUnitate)
        {
            //Setup(conn);
        }
              

    }
    [Serializable]
    public class CategorieSursa
    {
        public CategorieSursa(String nume, Int16 tag)
        {
            _Name = nume;
            _Tag = tag;
        }

        private String _Name = String.Empty;
        [System.ComponentModel.Bindable(true)]
        public String Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
            }
        }
        private Int16 _Tag = 0;
        [System.ComponentModel.Bindable(true)]
        public Int16 Tag
        {
            get
            {
                return _Tag;
            }
            set
            {
                _Tag = value;
            }
        }
    }
}
